export function SqlParser(tableName, comment) {

    /**
     * @param sqlData {Array}
     * @return {String}
     */
    this.resolve = function (sqlData) {
        let sqlFieldArray = [`CREATE TABLE IF NOT EXISTS ${tableName} (`];
        let indexFieldObject = {}, uniqueIndexFieldObject = {}, primaryKey = [], primaryKeyFieldObject = {};

        sqlData.forEach((field, index) => {
            //  一张表只能有一个主键(可以是联合主键)
            if(field.id == 'primary') { // 处理联合主键
                sqlFieldArray.push(`\t${field.name} ${field.type} ${field.notNull ? 'not null' : 'null'} PRIMARY KEY ${field.auto ? 'AUTO_INCREMENT' : ''} ${field.comment ? 'comment \''+field.comment+'\'' : ''}${index == sqlData.length -1 ? '' : ','}`);
            } else {
                let defaultValue = (field.default && field.default != 'null') ? field.default : null;
                sqlFieldArray.push(`\t${field.name} ${field.type} ${field.notNull ? 'not null' : 'null'} DEFAULT ${defaultValue} ${field.auto ? 'AUTO_INCREMENT' : ''} ${field.comment ? 'comment \''+field.comment+'\'' : ''}${index == sqlData.length -1 ? '' : ','}`);
                if(field.index) { // 用户已经输入索引名称
                    if(field.primary) {
                        primaryKey.push(`${field.name}`);
                        primaryKeyFieldObject[field.index] = true;
                    }

                    if(indexFieldObject[field.index]) {
                        indexFieldObject[field.index].push(field.name);
                    } else {
                        indexFieldObject[field.index] = [field.name];
                    }

                    if(field.unique) {
                        uniqueIndexFieldObject[field.index] = true;
                    }

                }

            }
        })
        sqlFieldArray.push(`) comment '${comment ? comment : ''}' Engine InnoDB;`)

        // 生成主键脚本
        if(primaryKey.length > 0) {
            sqlFieldArray.push(`ALTER TABLE ${tableName} ADD PRIMARY KEY (${primaryKey.join(',')});`)
        }

        // 生成索引脚本
        Object.keys(indexFieldObject).forEach(index => {
            let isPrimary = primaryKeyFieldObject[index];
            if(isPrimary) return; // 如果是主键则不需要再新增索引

            let join = indexFieldObject[index].join(',');
            let unique = uniqueIndexFieldObject[index];
            if(unique) {
                sqlFieldArray.push(`ALTER TABLE ${tableName} ADD UNIQUE ${index} (${join});`)
            } else {
                sqlFieldArray.push(`ALTER TABLE ${tableName} ADD INDEX ${index} (${join});`)
            }
        })

        return sqlFieldArray.join('\r\n');
    }
}